package org.darkforest.ucenter.auth;

import org.darkforest.vo.MemberBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by valentina on 15/3/6.
 * pc端权限验证
 */
public class AuthBySessionInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(AuthBySessionInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        return super.preHandle(request, response, handler);
        String url = request.getServletPath();
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
            AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);

            //没有声明需要权限,或者声明不验证权限
            if(authPassport == null || authPassport.isLogin() == true)
                return true;
            else{
                logger.debug("---check auth---");
                MemberBase member = (MemberBase)request.getSession().getAttribute("memInfo");
//                Cookie userId = CookieUtil.getCookieByName(request, "userId");
//                Cookie userName = CookieUtil.getCookieByName(request, "userName");
//                Cookie key = CookieUtil.getCookieByName(request, "key");
                if(member==null){
                    String basePath = (String)request.getSession().getServletContext().getAttribute("basePath");
                    response.sendRedirect(basePath+"/login?reUrl="+url);
//                    request.getRequestDispatcher("/login?reUrl="+url).forward(request,response);
                    return false;
                }
//                else {
//                    //如cookie未失效则认为依然处于登录状态,将cookie数据写入session，减少因session失效造成的多次登录
//                    MemberBase member = new MemberBase();
//                    member.setUserId(Integer.parseInt(userId.getValue()));
//                    member.setUserName(userName.getValue());
//                    request.getSession().setAttribute("memInfo",member);
//                    return true;
//                }
                return true;
            }
        }
        else
            return true;
    }
}
